/*
 *所有关于SheBei_Inspection类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*SheBei_InspectionService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using iMES.Core.BaseProvider;
using iMES.Core.DBManager;
using iMES.Core.Extensions;
using iMES.Core.Extensions.AutofacManager;
using iMES.Core.Utilities;
using iMES.Entity.DomainModels;
using IMES.SheBei.IRepositories;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using sys=System;
using System.Linq.Expressions;
using iMES.Custom.IRepositories;

namespace IMES.SheBei.Services
{
    public partial class SheBei_InspectionService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ISheBei_InspectionRepository _repository;//访问数据库
        private readonly IBase_NumberRuleRepository _inspectionRepository;//点检工单访问数据库
        [ActivatorUtilitiesConstructor]
        public SheBei_InspectionService(
            ISheBei_InspectionRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            IBase_NumberRuleRepository inspectionRepository
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _inspectionRepository = inspectionRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        WebResponseContent webResponse = new WebResponseContent();

        /// <summary>
        /// 新建
        /// <summary>
        /// <param name="saveDataModel"></param>
        /// <returns></returns>
        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            //此处saveModel是从前台提交的原生数据，可对数据进修改过滤
            AddOnExecuting = (SheBei_Inspection wo, object list) =>
            {
                if (string.IsNullOrEmpty(wo.SpotMaintWorkOrderCode))
                {
                    //如果没有点检工单编码，则生成一个新的点检工单编码
                    wo.SpotMaintWorkOrderCode = GetDeviceCode();
                }
                if(repository.Exists(x => x.SpotMaintWorkOrderCode == wo.SpotMaintWorkOrderCode))
                {
                    //如果点检工单编码已存在，则返回错误
                    return webResponse.Error("点检工单编码已存在，请重新输入！");
                    
                }
                return webResponse.OK();

            };
            
            return base.Add(saveDataModel);
        }
        /// <summary>
        /// 编辑操作
        /// <summary>
        /// <param name="saveDataModel"></param>
        /// <returns></returns>
        public override WebResponseContent Update(SaveModel saveModel)
        {
            UpdateOnExecute = (SaveModel model) =>
            {
                return webResponse.OK();
            };
            UpdateOnExecuting = (SheBei_Inspection wo, object addList, object updateList, List<object> delKeys) =>
            {
                return webResponse.OK();
            };
            return base.Update(saveModel);
        }

        public string CreateSpotWorkOrder()
        {
            try
            {
                object obj = DBServerProvider.SqlDapper.ExecuteScalar("GenerateSpotWorkOrder", new { }, sys.Data.CommandType.StoredProcedure);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return "生成成功！";
        }
        /// <summary>
        /// 自动生成设备编号
        /// </summary>
        /// <returns></returns>
        public string GetDeviceCode()
        {
            DateTime dateNow = (DateTime)DateTime.Now.ToString("yyyy-MM-dd").GetDateTime();
            //查询当天最新的订单号
            string defectItemCode = repository.FindAsIQueryable(x => x.CreateDate > dateNow && x.SpotMaintWorkOrderCode.Length > 8)
                .OrderByDescending(x => x.SpotMaintWorkOrderCode)
                .Select(s => s.SpotMaintWorkOrderCode)
                .FirstOrDefault();
            Base_NumberRule numberRule = _inspectionRepository.FindAsIQueryable(x => x.FormCode == "SpotMaintWorkOrder")
                .OrderByDescending(x => x.CreateDate)
                .FirstOrDefault();
            if (numberRule != null)
            {
                string rule = numberRule.Prefix + DateTime.Now.ToString(numberRule.SubmitTime.Replace("hh", "HH"));
                if (string.IsNullOrEmpty(defectItemCode))
                {
                    rule += "1".PadLeft(numberRule.SerialNumber, '0');
                }
                else
                {
                    rule += (defectItemCode.Substring(defectItemCode.Length - numberRule.SerialNumber).GetInt() + 1).ToString("0".PadLeft(numberRule.SerialNumber, '0'));
                }
                return rule;
            }
            else //如果自定义序号配置项不存在，则使用日期生成
            {
                return DateTime.Now.ToString("yyyyMMddHHmmssffff");
            }
        }
    }
}
